package com.tech.koufu.ui.activity.login;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.framework.utils.UIHandler;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;

import com.android.volley.AuthFailureError;
import com.android.volley.Request.Method;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.igexin.sdk.PushManager;
import com.tech.koufu.MyApplication;
import com.tech.koufu.R;
import com.tech.koufu.model.UserGroups;
import com.tech.koufu.tools.CoFoolAes;
import com.tech.koufu.tools.HttpUtils;
import com.tech.koufu.tools.KouFuTools;
import com.tech.koufu.tools.SharedConfig;
import com.tech.koufu.tools.Statics;

import android.R.bool;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * vipstart99
 * 123456
 * @ClassName: LoginActivity
 * @Description: TODO(这里用一句话描述这个类的作用)  
 * @author 123
 * @date 2015年5月31日 下午1:49:25
 */
public class LoginActivity extends Activity implements Callback,PlatformActionListener {
	private TextView tv_title,tv_righttitle;
	private EditText ed_username,ed_userpwd;
	private ImageView img_callback,img_wx,img_qq,img_wb;
	private Button btn_tologin;
	private String time;
	private static final int MSG_USERID_FOUND = 1;
	private static final int MSG_LOGIN = 2;
	private static final int MSG_AUTH_CANCEL = 3;
	private static final int MSG_AUTH_ERROR= 4;
	private static final int MSG_AUTH_COMPLETE = 5;
	MyApplication myApp;
	private Handler mHandler = new Handler();
	private StringRequest mRequest;
	private RequestQueue mQueue;
	private ArrayList<UserGroups> ugList;
	private String nickName = null;
	private String userId = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		myApp = (MyApplication)getApplication();
		initView();
	}

	private void initView(){
		String t = null;
		time = KouFuTools.readTimeInfo(t);
		mQueue = Volley.newRequestQueue(getApplicationContext());
		img_callback = (ImageView)findViewById(R.id.img_callback);
		img_callback.setVisibility(View.VISIBLE);
		img_callback.setOnClickListener(new myOnclickListener());
		tv_title = (TextView)findViewById(R.id.tv_title);
		tv_title.setVisibility(View.VISIBLE);
		tv_righttitle = (TextView)findViewById(R.id.tv_righttitle);
		tv_righttitle.setVisibility(View.VISIBLE);
		btn_tologin = (Button)findViewById(R.id.btn_tologin);
		btn_tologin.setOnClickListener(new myOnclickListener());
		tv_righttitle.setOnClickListener(new myOnclickListener());
		//		img_wx = (ImageView)findViewById(R.id.img_wx);
		//		img_wx.setOnClickListener(new myOnclickListener());
		img_qq = (ImageView)findViewById(R.id.img_qq);
		img_qq.setOnClickListener(new myOnclickListener());
		//		img_wb = (ImageView)findViewById(R.id.img_wb);
		//		img_wb.setOnClickListener(new myOnclickListener());
		ed_username = (EditText)findViewById(R.id.ed_username);
		ed_userpwd = (EditText)findViewById(R.id.ed_userpwd);
		String[] aaaus = SharedConfig.getLoginShares(getApplicationContext());
		if(aaaus!=null && aaaus.equals("sn")){
			ed_username.setText(aaaus[0]);
			ed_userpwd.setText(aaaus[1]);
		}
	}

	private class myOnclickListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			Intent intent = new Intent();
			switch (v.getId()) {
			case R.id.btn_tologin:
				time = KouFuTools.readTimeInfo(new String());
				String un = ed_username.getText().toString().trim();
				String up = ed_userpwd.getText().toString().trim();
				String des_up = KouFuTools.descrypt(up);
				if(un.equals("")){
					Toast.makeText(getApplicationContext(), "账号还没填写哟", Toast.LENGTH_SHORT).show();
				}else if(up.equals("")){
					Toast.makeText(getApplicationContext(), "密码还空着呢", Toast.LENGTH_SHORT).show();
				}else if(!un.equals("") && !up.equals("")){
					//					getUserInfo(un, des_up, "3");
					toLogin(un,up);
				}else{
					Toast.makeText(getApplicationContext(), "网络连接失败", Toast.LENGTH_SHORT).show();
				}
				//	intent.setClass(getApplicationContext(), MainContentFragment.class);
				//	startActivity(intent);
				break;
			case R.id.tv_righttitle:
				intent.setClass(getApplicationContext(), RegisterActivity.class);
				startActivity(intent);
				LoginActivity.this.finish();
				break;
			case R.id.img_callback:
				LoginActivity.this.finish();
				break;
			case R.id.img_qq:
				//				authorize(new QQ(getApplicationContext()));
				Platform qq = ShareSDK.getPlatform(QQ.NAME);
				authorize(qq);
				break;
				//			case R.id.img_wb:
				//				authorize(new SinaWeibo(getApplicationContext()));
				//				break;
			default:
				break;
			}
		}
	}

	private void authorize(Platform plat){
		//判断指定平台是否已经完成授权
		if(plat.isValid()) {
			userId = plat.getDb().getUserId().substring(19, plat.getDb().getUserId().length());
			nickName = plat.getDb().getUserName();
			if (userId != null) {
				UIHandler.sendEmptyMessage(MSG_USERID_FOUND, this);
//				login(plat.getName(), userId, null);
				return;
			}
		}
		plat.setPlatformActionListener(this);
		// true不使用SSO授权，false使用SSO授权
		plat.SSOSetting(true);
		//获取用户资料
		plat.showUser(null);
	}

	public void onComplete(Platform platform, int action,
			HashMap<String, Object> res) {
		if (action == Platform.ACTION_USER_INFOR) {
			UIHandler.sendEmptyMessage(MSG_AUTH_COMPLETE, this);
			userId = platform.getDb().getUserId().substring(19, platform.getDb().getUserId().length());
			nickName = platform.getDb().getUserName();
			login(platform.getName(), platform.getDb().getUserId(), res);

		}
		System.out.println(res);
		System.out.println("------User Name ---------" + platform.getDb().getUserName());
		System.out.println("------User ID ---------" + platform.getDb().getUserId());
	}

	public void onError(Platform platform, int action, Throwable t) {
		if (action == Platform.ACTION_USER_INFOR) {
			UIHandler.sendEmptyMessage(MSG_AUTH_ERROR, this);
		}
		t.printStackTrace();
	}

	public void onCancel(Platform platform, int action) {
		if (action == Platform.ACTION_USER_INFOR) {
			UIHandler.sendEmptyMessage(MSG_AUTH_CANCEL, this);
		}
	}

	private void login(String plat, String userId, HashMap<String, Object> userInfo) {
		Message msg = new Message();
		msg.what = MSG_LOGIN;
		msg.obj = plat;
		Log.v("QQ~Login~~Res", userId);
		UIHandler.sendMessage(msg, this);
	}
	
	private void toLogin(final String user,final String pwd){
		String url = Statics.URL_PHP+"login";
		mRequest = new StringRequest(Method.POST, url, new Response.Listener<String>() {

			@Override
			public void onResponse(String response) {
				 Log.d("login", response);
				try {
					if(!TextUtils.isEmpty(response)){
						ugList = new ArrayList<UserGroups>();
						JSONObject obj = new JSONObject(response);
						if(obj.getInt("status") == 0){
							JSONObject dataObj = new JSONObject(obj.getString("data"));
							JSONArray ugArray = new JSONArray(dataObj.getString("groups"));
							for(int i = 0 ; i < ugArray.length() ; i ++){
								UserGroups ug = new UserGroups(ugArray.getJSONObject(i));
								ugList.add(ug);
								if (ug.category == 1) {
									myApp.setUserid(ugList.get(i).group_id + "X" + dataObj.getInt("digitalid"));
									myApp.setUserName(dataObj.getString("userName"));
									myApp.setGroupId(""+ugList.get(i).group_id);
									myApp.setDigitalid(""+dataObj.getInt("digitalid"));
									myApp.setUserpwd(ed_userpwd.getText().toString().trim());
									myApp.webId = ""+ugList.get(i).web_id;
									myApp.url = KouFuTools.UrlChoose(ugList.get(i).web_id);
									myApp.isLogin = true;
									Log.w("MyApp.URL~~~~",ugList.get(i).web_id +"||" + myApp.url);
								}else{
									myApp.setUserid(ugList.get(0).group_id + "X" + dataObj.getInt("digitalid"));
									myApp.setUserName(dataObj.getString("userName"));
									myApp.setGroupId(""+ugList.get(0).group_id);
									myApp.setDigitalid(""+dataObj.getInt("digitalid"));
									myApp.setUserpwd(ed_userpwd.getText().toString().trim());
									myApp.url = KouFuTools.UrlChoose(ugList.get(0).web_id);
									myApp.isLogin = true;
									Log.w("MyApp.URL~~~~",ugList.get(0).web_id +"||" + myApp.url);
								}
								
							}
//							myApp.mUserGroups  = ugList;
							Toast.makeText(getApplicationContext(), "登录成功!", Toast.LENGTH_SHORT).show();
							SharedConfig.setLoginStatus(getApplicationContext(), ed_username.getText().toString().trim(), 
									ed_userpwd.getText().toString().trim(),System.currentTimeMillis(),"sn");
							Log.v("toLogin~~~~~~!", response); 
							Intent retIntent = new Intent();
							retIntent.putExtra("islogin", true);
							setResult(RESULT_OK,retIntent);
							LoginActivity.this.finish();
						}else{
							Toast.makeText(getApplicationContext(), obj.getString("error"), Toast.LENGTH_SHORT).show();
						}
					} 
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}, new Response.ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				// TODO Auto-generated method stub

			}
		}){

			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				Map<String, String> params = new HashMap<String, String>();
				params.put("userid", user);
				params.put("password", pwd);
				params.put("clientID", myApp.ClientID);
				//				params.put("clientID", PushManager.getInstance().getClientid(getApplicationContext()));
				return params;
			}		
			@Override
			protected Response<String> parseNetworkResponse(
					NetworkResponse response) {
				try { 
					Map<String, String> responseHeaders = response.headers;
					String rawCookies = responseHeaders.get("Set-Cookie"); 
					Log.v("Login~~SessionID===>", "rawCookies="+rawCookies);
					myApp.phpsessid = rawCookies;
										if(rawCookies!=null){
											String[] rwcs = rawCookies.split(";");
											String phpsessid = rwcs[0];
											phpsessid = phpsessid.substring(phpsessid.lastIndexOf("="));
											Log.e("TTTt", "phpsessid="+phpsessid);
											myApp.phpsessid = phpsessid;
										} 
					String dataString = new String(response.data, "UTF-8"); 
					return Response.success(dataString,HttpHeaderParser.parseCacheHeaders(response));
				} catch (UnsupportedEncodingException e) {
					return Response.error(new ParseError(e));
				} 
				//				return super.parseNetworkResponse(response);
			}
		};
		mQueue.add(mRequest);
	}

	private void loginForQQ(){
		String url = Statics.URL_PHP + "register_fromQQ";

		mRequest = new StringRequest(Method.POST, url, new Response.Listener<String>() {

			@Override
			public void onResponse(String response) {
				// TODO Auto-generated method stub
				Log.v("QQ~~~Response", response);
				if(!TextUtils.isEmpty(response)){
					try {
						ugList = new ArrayList<UserGroups>();
						JSONObject obj = new JSONObject(response);
						if(obj.getInt("status") == 0){
							JSONObject dobj = new JSONObject(obj.getString("data"));
							JSONArray ugArray = new JSONArray(dobj.getString("groups"));
							for(int i = 0 ; i < ugArray.length() ; i ++){
								UserGroups ug = new UserGroups(ugArray.getJSONObject(i));
								ugList.add(ug);
								if (ug.category == 1) {
									myApp.setUserid(ugList.get(i).group_id + "X" + dobj.getInt("digitalid"));
									myApp.setUserName(dobj.getString("userName"));
									myApp.setGroupId(""+ugList.get(i).group_id);
									myApp.setDigitalid(""+dobj.getInt("digitalid"));
									myApp.setUserpwd(ed_userpwd.getText().toString().trim());
									myApp.url = KouFuTools.UrlChoose(ugList.get(i).web_id);
									myApp.isLogin = true;
									Log.w("MyApp.URL~~~~",ugList.get(i).web_id +"||" + myApp.url);
								}
							} 
							Toast.makeText(getApplicationContext(), "登录成功!", Toast.LENGTH_SHORT).show();
							SharedConfig.setLoginStatus(getApplicationContext(), nickName, 
									userId,System.currentTimeMillis(),"qq");
							Log.e("MyAppliacation~~~~", myApp.getUserid());
							Log.v("toLogin~~~~~~!", response); 
							Intent retIntent = new Intent();
							retIntent.putExtra("islogin", true);
							setResult(RESULT_OK,retIntent); 
							LoginActivity.this.finish();
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}, new Response.ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				// TODO Auto-generated method stub

			}
		}){
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				// TODO Auto-generated method stub
				Map<String, String> params = new HashMap<String, String>();
				params.put("id", userId);
				params.put("nickname", nickName);
				params.put("clientID", myApp.ClientID);
				return params;
			}
			
			@Override
			protected Response<String> parseNetworkResponse(
					NetworkResponse response) {
				try { 
					Map<String, String> responseHeaders = response.headers; 
					String rawCookies = responseHeaders.get("Set-Cookie");  
					myApp.phpsessid = rawCookies; 
					String dataString = new String(response.data, "UTF-8"); 
					return Response.success(dataString,HttpHeaderParser.parseCacheHeaders(response));
				} catch (UnsupportedEncodingException e) {
					return Response.error(new ParseError(e));
				} 
				 
			}
		};
		mQueue.add(mRequest);
	}
	@Override
	public boolean handleMessage(Message msg) {
		// TODO Auto-generated method stub
		switch(msg.what) {
		case MSG_USERID_FOUND: {
			Toast.makeText(this, R.string.userid_found, Toast.LENGTH_SHORT).show();
			loginForQQ();
		}
		break;
		case MSG_LOGIN: {

			System.out.println("---------------");
			loginForQQ();

		}
		break;
		case MSG_AUTH_CANCEL: {
			Toast.makeText(this, R.string.auth_cancel, Toast.LENGTH_SHORT).show();
			System.out.println("-------MSG_AUTH_CANCEL--------");
		}
		break;
		case MSG_AUTH_ERROR: {
			Toast.makeText(this, R.string.auth_error, Toast.LENGTH_SHORT).show();
			System.out.println("-------MSG_AUTH_ERROR--------");
		}
		break;
		case MSG_AUTH_COMPLETE: {
			Toast.makeText(this, R.string.auth_complete, Toast.LENGTH_SHORT).show();
			System.out.println("--------MSG_AUTH_COMPLETE-------");
		}
		break;
		}
		return false;
	}
}
